package com.chs.recoginition.core.handler;

import com.chs.recoginition.core.exception.constant.ExceptionConstant;
import com.chs.recoginition.core.utils.JsonUtils;
import com.chs.recoginition.vo.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UnauthorizedHandler implements AuthenticationEntryPoint {

    /**
     * 未登录或无权限时触发的操作，提示未登录
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        // 返回json形式的错误信息
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().println(JsonUtils.toJson(Result.error(ExceptionConstant.UNAUTHORIZED)));
        response.getWriter().flush();
    }

}